package org.example.service.authorization.user;

import com.bianmaba.spring.web.service.BaseService;
import com.bianmaba.spring.security.util.PasswordEncoderFactory;
import org.apache.commons.lang3.StringUtils;
import org.example.bean.entity.authorization.User;
import org.example.repository.authorization.user.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * Created by cwx183898 on 2017/12/14.
 */
@Service
public class UserService extends BaseService<User, String> implements IUserService {
    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserRepository repository;


    @Override
    public UserRepository getRepository() {
        return repository;
    }

    @Override
    public User save(User entity) {
        PasswordEncoder passwordEncoder = PasswordEncoderFactory.getPasswordEncode("MD5");
        if (StringUtils.isEmpty(entity.getId())) {
            try {
                String user = SecurityContextHolder.getContext().getAuthentication().getName();
                entity.setCreator(user);
            } catch (Exception e) {
                entity.setCreator("SYSTEM");
            }
            String encodedPwd = passwordEncoder.encode(entity.getPassword());
            entity.setPassword("{MD5}" + encodedPwd);
        } else {
            User old = findOne(entity.getId());
            if (old != null) {
                if (!old.getPassword().equals(entity.getPassword())) {
                    String encodedPwd = passwordEncoder.encode(entity.getPassword());
                    entity.setPassword("{MD5}" + encodedPwd);
                }
            }
        }
        User user = super.save(entity);
        return user;
    }

    @Override
    public User findByUsername(String username) {
        User user = repository.findByUsername(username);
        return user;
    }
}
